#!/usr/bin/env python3
# -*- coding: utf-8 -*-

from logging.handlers import TimedRotatingFileHandler
import logging
import time
import os


class Logger:

    RESULTS_LOGS_PATH = os.path.dirname(os.path.abspath(__file__))

    def __init__(self, logger_name=__name__):
        self.logger = logging.getLogger(logger_name)
        logging.root.setLevel(logging.NOTSET)
        now_time = time.strftime("%Y-%m-%d_%H-%M-%S")
        self.log_file_name = '{0}.log'.format(now_time)
        if not os.path.exists(self.RESULTS_LOGS_PATH):
            os.makedirs(self.RESULTS_LOGS_PATH)
        self.log_file_path = os.path.join(self.RESULTS_LOGS_PATH, self.log_file_name)
        self.formatter = logging.Formatter(
            '[%(asctime)s][%(levelname)s]: %(message)s')
        self.console_output_level = 'INFO'
        self.file_output_level = 'DEBUG'
        self.backup_count = 20

    def get_logger(self, if_file_log=False):
        """在logger中添加日志句柄并返回，如果logger已有句柄，则直接返回"""
        if not self.logger.handlers:
            console_handler = logging.StreamHandler()
            console_handler.setLevel(self.console_output_level)
            console_handler.setFormatter(self.formatter)
            self.logger.addHandler(console_handler)
            if if_file_log:
                file_handler = TimedRotatingFileHandler(filename=self.log_file_path, when='D', interval=1,
                                                        backupCount=self.backup_count, delay=True, encoding='utf-8')
                file_handler.setLevel(self.file_output_level)
                file_handler.setFormatter(self.formatter)
                self.logger.addHandler(file_handler)
        return self.logger


logger = Logger().get_logger()
